package com.xyy.ec.pop.api.kingdinggmp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.xyy.ec.pop.api.kingdinggmp.config.ComentCfg;
import com.xyy.ec.pop.api.kingdinggmp.dto.erp.ErpSkuInfoDto;
import com.xyy.ec.pop.api.kingdinggmp.dto.erp.GmpCustomerDto;
import com.xyy.ec.pop.api.kingdinggmp.dto.erp.GmpStockDto;
import com.xyy.ec.pop.api.kingdinggmp.dto.pop.*;
import com.xyy.ec.pop.api.kingdinggmp.enums.TaskEnum;
import com.xyy.ec.pop.api.kingdinggmp.helpers.PopHelper;
import com.xyy.ec.pop.api.kingdinggmp.service.KingDingService;
import com.xyy.ec.pop.api.kingdinggmp.service.PopErpTaskService;
import com.xyy.ec.pop.api.kingdinggmp.service.PopService;
import com.xyy.ec.pop.api.kingdinggmp.utils.CfgUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PopErpTaskServiceImpl implements PopErpTaskService {
    @Autowired
    private PopService popService;
    @Autowired
    private KingDingService kingDingService;

    private ComentCfg comentCfg;

    {
        comentCfg = CfgUtils.getAppDefaultCfg();
    }

    /**
     * 商品全量
     */
    @Override
    public void syncProductFullToPop() {
        // 查询金蝶商品信息
        List<ErpSkuInfoDto> erpSkuInfoDtos = kingDingService.queryErpSkuInfo(new HashMap<>());
        List<PopErpSkuForInsertDto> erpSkuForInsertDtos = PopHelper.erpToPopSkuInfoConvert(erpSkuInfoDtos);
        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(comentCfg.getPopOrgId());
        taskQueryParam.setAppId(comentCfg.getPopAppId());
        taskQueryParam.setAppSecret(comentCfg.getPopAppSecret());
        taskQueryParam.setTaskId(TaskEnum.PRODUCT_FULL.getTaskId());
        taskQueryParam.setJsonData(JSON.toJSONString(erpSkuForInsertDtos));
        popService.pushDataInfo(taskQueryParam);

    }

    /**
     * 商品库存
     */
    @Override
    public void syncProductStockToPop() {
        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(comentCfg.getPopOrgId());
        taskQueryParam.setAppId(comentCfg.getPopAppId());
        taskQueryParam.setAppSecret(comentCfg.getPopAppSecret());
        taskQueryParam.setTaskId(TaskEnum.PRODUCT_STOCK.getTaskId());
        ApiRPCResult<ResultDto> resultDtoApiRPCResult = popService.queryTaskCondition(taskQueryParam);
        ResultDto data = JSON.parseObject(JSON.toJSONString(resultDtoApiRPCResult.getData()), ResultDto.class);
        if (ObjectUtil.isEmpty(data)) {
            log.warn("PopErpTaskServiceImpl.syncOrderStatePop# 【当前没有需要同步库存商品】");
            return;
        }
        QueryTaskData queryTaskData = JSON.parseObject(data.getDataJson(), QueryTaskData.class);
        String erpCodes = queryTaskData.getListQueryParam().stream().map(m -> "'" + m + "'").collect(Collectors.joining(","));
        List<GmpStockDto> gmpStockDtos = kingDingService.queryGmpStock(erpCodes, comentCfg.getSyncWarehouse());
        List<PopErpSkuStockV2Dto> popErpSkuStockV2Dtos = PopHelper.erpToPopStockConvert(gmpStockDtos);
        popErpSkuStockV2Dtos.addAll(syncSTockZero(queryTaskData.getListQueryParam(), popErpSkuStockV2Dtos));
        taskQueryParam.setJsonData(JSON.toJSONString(popErpSkuStockV2Dtos));
        popService.pushDataInfo(taskQueryParam);
        log.info("库存同步成功 成功条数: {}", popErpSkuStockV2Dtos.size());
    }

    // 查不到库存默认为0
    private List<PopErpSkuStockV2Dto> syncSTockZero(List<String> list, List<PopErpSkuStockV2Dto> popErpSkuStockV2Dtos) {
        List<PopErpSkuStockV2Dto> popErpSkuStockV2DtoList = new ArrayList<>();
        List<String> erpList = popErpSkuStockV2Dtos.stream().map(m -> m.getErpCode()).collect(Collectors.toList());
        // 删除有库存商品
        list.removeAll(erpList);
        // 没库存制0
        for (String erpCode : list) {
            PopErpSkuStockV2Dto popErpSkuStockV2Dto = new PopErpSkuStockV2Dto();
            popErpSkuStockV2Dto.setErpCode(erpCode);
            popErpSkuStockV2Dto.setAvailableQyt(0);
            popErpSkuStockV2DtoList.add(popErpSkuStockV2Dto);
        }
        return popErpSkuStockV2DtoList;
    }

    /**
     *
     */
    @Override
    public void syncProductPriceToPop() {
        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(comentCfg.getPopOrgId());
        taskQueryParam.setAppId(comentCfg.getPopAppId());
        taskQueryParam.setAppSecret(comentCfg.getPopAppSecret());
        taskQueryParam.setTaskId(TaskEnum.PRODUCT_PRICE.getTaskId());
        ApiRPCResult<ResultDto> resultDtoApiRPCResult = popService.queryTaskCondition(taskQueryParam);
        ResultDto data = JSON.parseObject(JSON.toJSONString(resultDtoApiRPCResult.getData()), ResultDto.class);
        if (ObjectUtil.isEmpty(data)) {
            log.warn("PopErpTaskServiceImpl.syncOrderStatePop# 【当前没有需要同步价格商品】");
            return;
        }
        QueryTaskData queryTaskData = JSON.parseObject(data.getDataJson(), QueryTaskData.class);
        String erpCodes = queryTaskData.getListQueryParam().stream().map(m -> "'" + m + "'").collect(Collectors.joining(","));
        // 调用金蝶接口查询物料
        List<ErpSkuInfoDto> erpSkuInfoDtos = kingDingService.queryErpSkuPriceInfo(erpCodes);
        List<PopErpSkuPriceDto> popErpSkuPriceDtos = PopHelper.erpToPopPriceConvert(erpSkuInfoDtos);
        taskQueryParam.setJsonData(JSON.toJSONString(popErpSkuPriceDtos));
        popService.pushDataInfo(taskQueryParam);
        log.info("价格同步成功 成功条数: {}", popErpSkuPriceDtos.size());


    }

    /**
     * 客户信息上报
     */
    @Override
    public void syncCustomerToPop() {
        // 构建请求参数
        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(comentCfg.getPopOrgId());
        taskQueryParam.setAppId(comentCfg.getPopAppId());
        taskQueryParam.setAppSecret(comentCfg.getPopAppSecret());
        taskQueryParam.setTaskId(TaskEnum.CLIENT_INFO.getTaskId());
        // 查询金蝶客户客户信息
        List<GmpCustomerDto> gmpCustomerDtoList = kingDingService.queryGmpCustomer(comentCfg.getIsFullSync());
        // 转成平台客户信息
        List<PopErpClientInfoDto> popErpClientInfoDtoList = PopHelper.erpToPopCustomerConvert(gmpCustomerDtoList);
        taskQueryParam.setJsonData(JSON.toJSONString(popErpClientInfoDtoList));
        popService.pushDataInfo(taskQueryParam);
    }

    /**
     * 订单导入
     */
    @Override
    public void syncOrderToMerchant() {
        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(comentCfg.getPopOrgId());
        taskQueryParam.setAppId(comentCfg.getPopAppId());
        taskQueryParam.setAppSecret(comentCfg.getPopAppSecret());
        taskQueryParam.setTaskId(TaskEnum.ORDER_TOTAL.getTaskId());
        ApiRPCResult<ResultDto> resultDtoApiRPCResult = popService.pullDataInfo(taskQueryParam);
        ResultDto data = JSON.parseObject(JSON.toJSONString(resultDtoApiRPCResult.getData()), ResultDto.class);
        if (ObjectUtil.isEmpty(data)) {
            log.warn("PopErpTaskServiceImpl.syncOrderToMerchant# 【当前没有需要导入订单信息】");
            return;
        }
        List<SellerOrderInfoDto> sellerOrderInfoDtos = JSON.parseArray(data.getDataJson(), SellerOrderInfoDto.class);
        Map<String, String> orderConfig = new HashMap<>();
        orderConfig.put("orgId", comentCfg.getPopOrgId());
        orderConfig.put("FSalerId", comentCfg.getOrderSales());
        orderConfig.put("FBusinessId", comentCfg.getOrderBus());
        List<SellerOrderCallBackDto> sellerOrderCallBackDtos = kingDingService.saveOrderInfo(sellerOrderInfoDtos, orderConfig);
        taskQueryParam.setJsonData(JSON.toJSONString(sellerOrderCallBackDtos));
        popService.callbackForPullTask(taskQueryParam);
    }

    /**
     * 客户导入
     */
    @Override
    public void syncNoneOpenCustomerToMerchant() {
        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(comentCfg.getPopOrgId());
        taskQueryParam.setAppId(comentCfg.getPopAppId());
        taskQueryParam.setAppSecret(comentCfg.getPopAppSecret());
        taskQueryParam.setTaskId(TaskEnum.CLIENT_PUSH_DOWN.getTaskId());
        ApiRPCResult<ResultDto> resultDtoApiRPCResult = popService.pullDataInfo(taskQueryParam);
        ResultDto data = JSON.parseObject(JSON.toJSONString(resultDtoApiRPCResult.getData()), ResultDto.class);
        if (ObjectUtil.isEmpty(data)) {
            log.warn("PopErpTaskServiceImpl.syncNoneOpenCustomerToMerchant# 【当前没有需要导入客户信息】");
            return;
        }
        List<PlatformCustomerDto> platformCustomerDtos = JSON.parseArray(data.getDataJson(), PlatformCustomerDto.class);
        Map<String, String> customerCfgMap = new HashMap<>();
        customerCfgMap.put("FSTAFFNUMBER", comentCfg.getCustomerSale());
        customerCfgMap.put("orgId", comentCfg.getPopOrgId());
        customerCfgMap.put("FGroup", comentCfg.getCustomerGroup());
        List<SellerCustomerCallBackDto> sellerCustomerCallBackDtos = kingDingService.saveCustomer(platformCustomerDtos, customerCfgMap);
        taskQueryParam.setJsonData(JSON.toJSONString(sellerCustomerCallBackDtos));
        popService.callbackForCustomerPullTask(taskQueryParam);

    }

    /**
     * 出库明细同步
     */
    @Override
    public void syncOrderStatePop() {
        TaskQueryParam taskQueryParam = new TaskQueryParam();
        taskQueryParam.setOrgId(comentCfg.getPopOrgId());
        taskQueryParam.setAppId(comentCfg.getPopAppId());
        taskQueryParam.setAppSecret(comentCfg.getPopAppSecret());
        taskQueryParam.setTaskId(TaskEnum.ORDER_DELIVERY_DETAILE.getTaskId());
        ApiRPCResult<ResultDto> resultDtoApiRPCResult = popService.queryTaskCondition(taskQueryParam);
        ResultDto data = JSON.parseObject(JSON.toJSONString(resultDtoApiRPCResult.getData()), ResultDto.class);
        if (ObjectUtil.isEmpty(data)) {
            log.warn("PopErpTaskServiceImpl.syncOrderStatePop# 【当前没有需要出库订单】");
            return;
        }
        QueryTaskData queryTaskData = JSON.parseObject(data.getDataJson(), QueryTaskData.class);
        List<String> listQueryParam = queryTaskData.getListQueryParam();
        List<SellerOrderDeliverDetailForErpDto> outOrderList = new ArrayList<>();
        for (String order : listQueryParam) {
            outOrderList.addAll(kingDingService.queryOutOrderList(order));
        }
        taskQueryParam.setJsonData(JSON.toJSONString(outOrderList));
        popService.pushDataInfo(taskQueryParam);
    }

    /**
     * 物流信息同步
     */
    @Override
    public void syncOrderDeliverInfo() {

    }

    /**
     * 电子发票
     */
    @Override
    public void syncOrderInvoice() {

    }

    /**
     * 已开单
     */
    @Override
    public void syncOrderDone() {

    }
}
